package com.opages.transaction.message.daemon.scheduled;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.opages.transaction.message.api.TransactionMessageApi;
import com.opages.transaction.message.common.utils.HttpClientTool;
import com.opages.transaction.message.daemon.config.MessageProperties;
import com.opages.transaction.message.model.TransactionMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * @Title: MessageDeal.java
 * @Description: TODO(用一句话描述该文件做什么)
 * @author LDZ
 * @date 2018年3月6日 下午5:04:55
 */
@Component("messageDeal")
public class MessageDeal {
	private static final Log log = LogFactory.getLog(MessageDeal.class);
	@Value("#{configproperties_no_reloadable_disconf['ali.transaction.alarm.phone']}")
	private String alarmPhone;
	@Value("#{configproperties_no_reloadable_disconf['ali.transaction.alarm.templateCode']}")
	private String templateCode;

	@Autowired
	private MessageProperties messageProperties;
	@Autowired
	private TransactionMessageApi transactionMessageApi;

	/**
	 * 处理[待确认]状态的消息
 	 * @param messageMap
	 */
	public void handleWaitingConfirmTimeOutMessages(Map<String, TransactionMessage> messageMap) {
		log.debug("开始处理[待确认]状态的消息,总条数[" + messageMap.size() + "]");
		// 单条消息处理
		for (Map.Entry<String, TransactionMessage> entry : messageMap.entrySet()) {
			TransactionMessage message = entry.getValue();
			try {
				log.debug("开始处理[待确认]消息ID为[" + message.getUuid() + "]的消息");
				String callbackUrl = message.getMsgConfirmUrl();
				String result = HttpClientTool.getString(callbackUrl);
				if("true".equals(result)) {
					System.err.println("------------业务操作成功，更新消息状态并进行投递！！！！");
					// 确认并发送消息
					transactionMessageApi.confirmAndSendMessage(message.getUuid());
				}else if("false".equals(result)){
					System.err.println("------------业务操作失败，删除消息！！！！");
					log.debug("订单没有支付成功,删除[待确认]消息id[" + message.getUuid() + "]的消息");
					transactionMessageApi.deleteMessageByMessageId(message.getUuid());
				}

				System.err.println("---------------处理[待确认]状态的消息-----------------");
				log.debug("结束处理[待确认]消息ID为[" + message.getUuid() + "]的消息");
			} catch (Exception e) {
				log.error("处理[待确认]消息ID为[" + message.getUuid() + "]的消息异常：", e);
			}
		}
	}

	/**
	 * 处理[发送中]状态的消息
	 * @param messageMap
	 */
	public void handleSendingTimeOutMessage(Map<String, TransactionMessage> messageMap) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		log.debug("开始处理[发送中]状态的消息,总条数[" + messageMap.size() + "]");

		// 根据配置获取通知间隔时间
		Map<Integer, Integer> notifyParam = getSendTime();

		// 单条消息处理
		for (Map.Entry<String, TransactionMessage> entry : messageMap.entrySet()) {
			TransactionMessage message = entry.getValue();
			try {
				log.debug("开始处理[发送中]消息ID为[" + message.getUuid() + "]的消息");
				// 判断发送次数
				int maxTimes = messageProperties.getSender().getMaxTimes();
				log.debug("[发送中]消息ID为[" + message.getUuid() + "]的消息,已经重新发送的次数[" + message.getMessageSendTimes() + "]");

				// 如果超过最大发送次数直接退出
				if (maxTimes < message.getMessageSendTimes()) {
					// 标记为死亡
					System.err.println("-------处理[发送中]状态的消息----超过最大发送次数【"+message.getMessageSendTimes()+"】，将消息标记为死亡.");
					transactionMessageApi.setMessageToAreadlyDead(message.getUuid());
					//发送消息
					//消息UUID为${uuid}类型为${msgType}队列名称为${queueName}的由于未知原因处理不成功，请尽快处理，时间${createTime}
					Map<String, String> params = new HashMap<>();
					//阿里云不允许超过20位的uuid作为参数，因此改为主键，系统可根据主键查询uuid来
					params.put("uuid", message.getId().toString());
					params.put("msgType", message.getConsumerQueue());
					params.put("queueName", message.getConsumerQueue());
					params.put("createTime", sdf.format(message.getInsertDatetime()));
//					SendSmsResponse response = AliMsg.sendSms(alarmPhone, templateCode, params, null);
					continue;
				}
				// 判断是否达到发送消息的时间间隔条件
				int reSendTimes = message.getMessageSendTimes();
				int times = notifyParam.get(reSendTimes == 0 ? 1 : reSendTimes);
				long currentTimeInMillis = Calendar.getInstance().getTimeInMillis();
				long needTime = currentTimeInMillis - times * 60 * 1000;
				long hasTime = message.getUpdateDatetime().getTime();
				// 判断是否达到了可以再次发送的时间条件
				if (hasTime > needTime) {
					log.debug("currentTime[" + sdf.format(new Date()) + "],[发送中]消息上次发送时间[" + sdf.format(message.getUpdateDatetime()) + "],必须过了[" + times + "]分钟才可以再发送。");
					continue;
				}

				// 重新发送消息
				System.err.println("-------处理[发送中]状态的消息----重新发送消息------");
				transactionMessageApi.reSendMessage(message);

				log.debug("结束处理[发送中]消息ID为[" + message.getUuid() + "]的消息");
			} catch (Exception e) {
				log.error("处理[发送中]消息ID为[" + message.getUuid() + "]的消息异常：", e);
			}
		}

	}

	/**
	 * 根据配置获取通知间隔时间
	 *
	 * @return
	 */
	private Map<Integer, Integer> getSendTime() {
		Map<Integer, Integer> notifyParam = new HashMap<Integer, Integer>();
		notifyParam.put(1, messageProperties.getSender().getOneTime());
		notifyParam.put(2, messageProperties.getSender().getTwoTime());
		notifyParam.put(3, messageProperties.getSender().getThreeTime());
		notifyParam.put(4, messageProperties.getSender().getFourTime());
		notifyParam.put(5, messageProperties.getSender().getFiveTime());
		return notifyParam;
	}
}
